package cn.com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
//import org.apache.commons.httpclient.HttpStatus;//此类需要添加maven依赖或jar包
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpUtils {

	public static String doGet(String urlPath, HashMap<String, Object> params) throws Exception {
		StringBuilder sb = new StringBuilder(urlPath);
		if (params != null && !params.isEmpty()) { // 说明有参数
			sb.append("?");

			Set<Entry<String, Object>> set = params.entrySet();
			for (Entry<String, Object> entry : set) { // 遍历map里面的参数
				String key = entry.getKey();
				String value = "";
				if (null != entry.getValue()) {
					value = entry.getValue().toString();
					// 转码
					value = URLEncoder.encode(value, "UTF-8");
				}
				sb.append(key).append("=").append(value).append("&");
			}

			sb.deleteCharAt(sb.length() - 1); // 删除最后一个&
		}
		URL url = new URL(sb.toString());
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000); // 5s超时
		conn.setRequestMethod("GET");

		if (conn.getResponseCode() == 200) {// HttpStatus.SC_OK ==
			// 200
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			StringBuilder sbs = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				sbs.append(line);
			}
			return sbs.toString();
		}

		return null;
	}

	public static String doPost(String urlPath, String jsonParams) throws Exception {

		try {
			// 创建 HttpClient 实例
			CloseableHttpClient httpClient = HttpClients.createDefault();

			// 创建 POST 请求
			HttpPost httpPost = new HttpPost(urlPath);

			// 设置请求头
			httpPost.setHeader("Content-Type", "application/json");
			httpPost.setHeader("Accept", "application/json");

			// 设置请求体（JSON 参数）
			StringEntity entity = new StringEntity(jsonParams, "UTF-8");
			httpPost.setEntity(entity);
			String responseBody = "";
			// 执行请求并获取响应
			try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
				int statusCode = response.getStatusLine().getStatusCode();
				log.info("状态码: " + statusCode);

				responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
				log.info("响应内容: " + responseBody);

			}
			// 关闭 HttpClient
			httpClient.close();
			return "响应内容: " + responseBody;
		} catch (IOException e) {
			e.printStackTrace();
			log.error("异常：" + e.getMessage());
			return "异常：" + e.getMessage();
		}

	}
}
